package top.huacc.aliyun.facebody;

import com.aliyun.imageseg20191230.Client;
import com.aliyun.imageseg20191230.models.SegmentBodyAdvanceRequest;
import com.aliyun.imageseg20191230.models.SegmentBodyRequest;
import com.aliyun.imageseg20191230.models.SegmentBodyResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 人体分割工具类
 * 提供人脸模板管理和人体分割功能
 */
@Slf4j
public class FaceFusionUtils {
    
    /**
     * 人体分割服务Endpoint
     */
    private static final String ENDPOINT = "imageseg.cn-shanghai.aliyuncs.com";

    /**
     * 创建阿里云人体分割服务客户端
     *
     * @return Client 人体分割服务客户端
     * @throws Exception 创建客户端异常
     */
    public static Client createClient(String ACCESS_KEY_ID, String ACCESS_KEY_SECRET) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        // 设置访问的域名
        config.endpoint = ENDPOINT;
        return new Client(config);
    }

    /**
     * 人体分割
     *
     * @param imageUrl 用户上传的人脸图片URL
     * @return 融合后的人脸图片Base64编码数据
     * @throws Exception 人体分割异常
     */
    public static String humanBodySegmentation(String imageUrl, String ACCESS_KEY_ID, String ACCESS_KEY_SECRET) throws Exception {
        Client client = createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        RuntimeOptions runtime = new RuntimeOptions();
        SegmentBodyResponse response;
        if (imageUrl.contains("shanghai")) {
            SegmentBodyRequest request = new SegmentBodyRequest()
                    .setImageURL(imageUrl);
            response = client.segmentBodyWithOptions(request, runtime);
        } else {
            URL url = new URL(imageUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            urlConnection.setReadTimeout(10000);
            InputStream inputStream = urlConnection.getInputStream();
            SegmentBodyAdvanceRequest request = new SegmentBodyAdvanceRequest().setImageURLObject(inputStream);
            response = client.segmentBodyAdvance(request, runtime);
        }
        try {
            return response.getBody().getData().getImageURL();
        } catch (TeaException teaException) {
            log.error("人体分割失败: {}", teaException.getMessage(), teaException);
            throw new Exception("人体分割失败: " + teaException.getMessage());
        } catch (Exception exception) {
            log.error("人体分割异常: {}", exception.getMessage(), exception);
            throw new Exception("人体分割异常: " + exception.getMessage());
        }
    }

    public static String humanBodySegmentation(InputStream imageURLObject, String ACCESS_KEY_ID, String ACCESS_KEY_SECRET) throws Exception {
        Client client = createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        SegmentBodyAdvanceRequest request = new SegmentBodyAdvanceRequest().setImageURLObject(imageURLObject);
        SegmentBodyResponse response = client.segmentBodyAdvance(request, new RuntimeOptions());
        try {
            return response.getBody().getData().getImageURL();
        } catch (TeaException teaException) {
            log.error("人体分割失败: {}", teaException.getMessage(), teaException);
            throw new Exception("人体分割失败: " + teaException.getMessage());
        } catch (Exception exception) {
            log.error("人体分割异常: {}", exception.getMessage(), exception);
            throw new Exception("人体分割异常: " + exception.getMessage());
        }
    }

}
